# -*- coding:utf-8 -*-
from django.shortcuts import render
import time
import os
import datetime
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.template import Template, Context, RequestContext
from django.template.loader import get_template
from templatetags import substring
from django.shortcuts import render_to_response, render, get_object_or_404
from django.db import connection
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.csrf import csrf_exempt    #不用csrf
from django.http import Http404
from django.core import serializers
import json
import httplib2
import logging
import urllib
from django.core.paginator import Paginator,InvalidPage,EmptyPage
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django import forms
from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
from django.contrib.messages import constants as messages
from django.contrib import messages
from django.contrib.auth.models import User
from home.models import DevModules

logger=logging.getLogger(__name__)

def trace(msg):
    now=time.strftime("%Y-%m-%d %H:%M:%S")
    print "["+now+"]",msg

def home(request):
    name = "wongjian"
    logger.info(name)
    return render_to_response("home/home.html",context_instance=RequestContext(request))


def download(request):
    moduel_name = "all"
    all_list={}
    title="搜狐前端开发资源包"

    mode_list=DevModules.objects.all().order_by("-pk")

    for index,modules in enumerate(mode_list):
       try:
           all_list[modules.module_name]
       except KeyError:
           all_list[modules.module_name]=[]
       all_list[modules.module_name].append(modules.toDict())

    cont={
        "title": title,
        "module_name":moduel_name,
        "all_mode":all_list,
        "mode_list":mode_list
    }
    return render_to_response("home/download.html", cont)


def downProject(request,project):
    dir_list = []
    mode_list=DevModules.objects.filter(module_name=project.lower())
    title=mode_list[0].project_name
    devCookie=None
    minCookie=None

    for mod in mode_list:
        dir_list.append(mod.toDict())

    if project+"_dev" in request.COOKIES:
       devCookie=request.COOKIES[project+"_dev"]

    if project+"_min" in request.COOKIES:
       minCookie=request.COOKIES[project+"_min"]

    cont={
        "title": title,
        "module_name":project,
        "filelist":dir_list,
        "devCookie":devCookie,
        "minCookie":minCookie,
    }
    return render_to_response("home/download.html", cont)


def downModule(request,project,id):
    dir_list = []
    mode_list=DevModules.objects.get(pk=id)
    dir_list.append(mode_list.toDict())
    devCookie=None
    minCookie=None

    if project+"_dev" in request.COOKIES:
       devCookie=request.COOKIES[project+"_dev"]

    if project+"_min" in request.COOKIES:
       minCookie=request.COOKIES[project+"_min"]

    cont={
        "title": project,
        "module_name":project,
        "filelist":dir_list,
        "module_type":mode_list.module_type,
        "modify_time":mode_list.modify_time,
        "alert":True,
        "devCookie":devCookie,
        "minCookie":minCookie
    }
    return render_to_response("home/download.html", cont)

@csrf_exempt
def chgModInfo(request,project,version,type):
    zip=request.POST.get("zip","")
    size=request.POST.get("size","")
    modify_time=request.POST.get("modify_time","")
    md5=request.POST.get("md5","")
    project_url=request.POST.get("project_url","")
    module_path=request.POST.get("module_path","")
    notify=True if request.POST.get("notify")=="True" else False
    content={}

    res=DevModules.objects.filter(

        module_name=project,
        project_version=version,
        module_type=type).update(

        #set the list value
        zip=zip,
        size=size,
        md5=md5,
        notify=notify,
        modify_time=modify_time,
        project_url=project_url,
        module_path=module_path
    )
    if res:
        content["status"]="successful"
    else:
        content["status"]="fail"

    return HttpResponse(json.dumps(content), content_type="application/json")


def addCookie(request):
     content={}
     project=request.GET.get("project","")
     type=request.GET.get("type","")
     md5=request.GET.get("md5","")
     cookieName=project+"_"+type
     response=None

     dt = datetime.datetime.now() + datetime.timedelta(hours = int(1))

     if cookieName in request.COOKIES:
         value=request.COOKIES[cookieName]
         if md5 != value:
            content["status"]="successful"
            response= HttpResponse(json.dumps(content), content_type="application/json")
            response.set_cookie(cookieName,md5,expires=dt)
         else:
            content["status"]="fail"
            response= HttpResponse(json.dumps(content), content_type="application/json")
     else:
        content["status"]="successful"
        response= HttpResponse(json.dumps(content), content_type="application/json")
        response.set_cookie(cookieName,md5,expires=dt)
     return response


def cok(request):
   cont={}

   if "favorite_color" in request.COOKIES:
       value=request.COOKIES["favorite_color"]
       cont["world"]=value
   else:
       cont["world"]="not"

   response=render_to_response("home/cookies.html",cont)

   response.set_cookie("favorite_color","yellow")

   #response.delete_cookie("favorite_color",path="/",domain="127.0.0.1")

def session(request):
  request.session["fav_color"]="blue"
  del request.session["fav_color"]

  if "fav_color" in request.session:
      fav_color=request.session["fav_color"]

      return HttpResponse(fav_color)
  else:
      return  HttpResponse("none")

def sayHi(request):
    res=DevModules.objects.get(id=2)
    logger.info(res)
    return HttpResponse("test")



